package cn.com.oil.common.util;

import cn.com.oil.common.model.FileSystemNode;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;

@Slf4j
public class FileUtils {

    public static String getCachePath() {
        // 使用 ClassLoader 加载资源文件
        String rootPath = commonRootPath();
        StringBuilder stringBuilder = new StringBuilder();
        try {
            InputStream inputStream = Files.newInputStream(new File(rootPath + "/data/cache.json").toPath());
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    stringBuilder.append(line).append("\n");
                }
            }
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        return stringBuilder.toString();
    }

    public static JSONObject getCacheJSon() {
        String cachePath = FileUtils.getCachePath();
        return JSONUtil.parseObj(cachePath);
    }

    public static Path commonPath() {
        ClassPathResource resource = new ClassPathResource(getCacheJSon().get("projectPath", String.class));
        Path filePath = null;
        try {
            File file = resource.getFile();
            if (!file.exists()) {
                file.mkdirs();
            }
            filePath = file.toPath();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return filePath;
    }


    public static void setCacheJSon(JSONObject entries) {
        String stringPretty = entries.toStringPretty();
        String filePath = commonRootPath();
        String format = String.format("%s/%s", filePath.replace("\\", "/"), "cache.json");
        File file = new File(format);
        try (FileWriter writer = new FileWriter(file)) {
            writer.write(stringPretty);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }

    public static FileSystemNode getMenu(String name) {
        Path filePath = commonPath();
        File file = new File(String.format("%s/%s", filePath, name));
        return buildTree(file, null);
    }


    public static FileSystemNode buildTree(File directory, FileSystemNode parent) {
        FileSystemNode node = new FileSystemNode(directory.getName(), directory.isDirectory(), parent);
        File[] files = directory.listFiles();
        for (File file : files) {
            FileSystemNode child = new FileSystemNode(file.getName(), file.isDirectory(), node);
            if (file.isDirectory()) {
                // 递归构建子目录
                child = buildTree(file, node);
            }
            node.addChild(child);
        }
        return node;
    }

    public static void initCreateDir() {
        String rootPath = getCacheJSon().get("rootPath", String.class);
        String filePath = commonRootPath();
        String projectPath = filePath.replace("\\", "/").replace(rootPath, getCacheJSon().get("projectPath", String.class));
        File file = new File(projectPath);
        file.mkdirs();
    }

    public static String commonRootPath() {
        return System.getProperty("user.dir");
    }


    public static boolean isExistDir(String name) {
        Path filePath = commonPath();
        String absolutePath = filePath.toFile().getAbsolutePath();
        String projectPath = String.format("%s/%s", absolutePath.replace("\\", "/"), name);
        File file = new File(projectPath);
        return file.exists();
    }

    public static FileSystemNode CreateDir(String name) {
        Path filePath = commonPath();
        String absolutePath = filePath.toFile().getAbsolutePath();
        String projectPath = String.format("%s/%s", absolutePath.replace("\\", "/"), name);
        File file = new File(projectPath);
        file.mkdirs();
        createDefaultDic(file);

        return getMenu(name);
    }

    private static void createDefaultDic(File file) {
        // todo 创建一些默认的文件夹
        // 要创建的子目录名称列表
        String[] subDirectoryNames = {"subdir1", "subdir2", "subdir3"};

        // 创建子目录
        for (String subDirectoryName : subDirectoryNames) {
            File subDirectory = new File(file, subDirectoryName);
            if (!subDirectory.exists()) {
                boolean created = subDirectory.mkdirs();
                if (created) {
                    System.out.println("子目录 " + subDirectoryName + " 创建成功");
                } else {
                    System.out.println("未能创建子目录 " + subDirectoryName);
                }
            } else {
                System.out.println("子目录 " + subDirectoryName + " 已存在");
            }
        }
    }

}
